//
//  FriendApplyViewController.m
//  Molian
//
//  Created by wansong on 4/16/15.
//  Copyright (c) 2015 xiaocan. All rights reserved.
//

#import "FriendApplyViewController.h"
#import "FriendApplyCell.h"
#import "MLUserDataViewController.h"

@interface FriendApplyViewController ()
// 好友申请列表
@property (nonatomic, strong)NSMutableArray *friendApplyList;

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)Utils * uview;

@end

@implementation FriendApplyViewController


-(void)cmd:(NSNotification *)notification
{
    NSDictionary *dic=[notification userInfo];
    EMMessage *message = [dic objectForKey:@"message"];
    if ([message.from isEqualToString:@"new_friend"]) {
        [self loadFriendApplyData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"新的好友";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    [self loadFriendApplyData];
    // 右上角按钮
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithTitle:@"忽略所有" style:UIBarButtonItemStyleBordered target:self action:@selector(rejectAllApply)];
    [rightBarButton setTintColor:[UIColor whiteColor]];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    self.friendApplyList = [NSMutableArray array];

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.tableHeaderView = [[UIView alloc] init];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorColor = RGBA(225, 225, 225, 1);//分隔条颜色
    [self.view addSubview:self.tableView];
    self.uview = [[Utils alloc]init];
    [_uview viewControllerPrompt:self.view.bounds Text:@"没有新的好友~" Image:[UIImage imageNamed:@"xinlianren_nul"]];
    [self. view addSubview:_uview.viewPrompt];
     if ([self.friendApplyList count] == 0) {
          _uview.viewPrompt.hidden = NO;
     }else{
          _uview.viewPrompt.hidden = YES;
     }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cmd:) name:@"cmd" object:nil];
  
}
- (void)dealloc
{
     [[NSNotificationCenter defaultCenter] removeObserver:self];
   // [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cmd" object:nil];
    
}
// 加载好友申请列表
- (void)loadFriendApplyData {
    AVQuery *friendApplyQuery = [MLFriendApply query];
    [friendApplyQuery whereKey:@"user" equalTo:[MLUser currentUser]];
    [friendApplyQuery includeKey:@"applier"];
    [friendApplyQuery whereKey:@"status" equalTo:[NSNumber numberWithInt:MLFriendApplyStatus_WAITING]];
    [friendApplyQuery orderByDescending:@"updatedAt"];
    [friendApplyQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            for (MLFriendApply *article in objects) {
                if (article.user) {
                    [self.friendApplyList addObject:article];
                }else{
                    [article deleteInBackground];
                }
            }
            
            if ([self.friendApplyList count] == 0) {
                _uview.viewPrompt.hidden = NO;
            }else{
                 _uview.viewPrompt.hidden = YES;
                [self.tableView reloadData];
            }
        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

#pragma mark tableview delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static  NSString *CellIdentifier = @"FriendApplyCell";
    FriendApplyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        cell = [[FriendApplyCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    // 如果列表为空直接返回
    if ([self.friendApplyList count] == 0) {
        return cell;
    }
    MLFriendApply *friendApply = self.friendApplyList[indexPath.row];
    MLUser *applier = (MLUser *)friendApply.applier;
    
    cell.userNameLabel.text = applier.nickname;
  //  [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:applier.avatar.url] placeholderImage:[UIImage imageWithColor:[UIColor whiteColor]]];
    if (!applier.subAvatar || [applier.subAvatar isEqualToString:@""]) {
        [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:applier.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
        
    }else{
        [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:applier.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
    }
    [cell.userAgeLabel setTitle:[NSString stringWithFormat:@"%ld", (long)[applier getUserAge]] forState:UIControlStateNormal];
    if (applier.gender == MLUserGender_MALE) {
        [cell.userAgeLabel setBackgroundImage:[UIImage imageNamed:@"boy_age"] forState:UIControlStateNormal];
    } else {
        [cell.userAgeLabel setBackgroundImage:[UIImage imageNamed:@"girl_age"] forState:UIControlStateNormal];
    }
    
    NSString *city = applier.selectCity?applier.selectCity:@"";
    NSString *strH = applier.height?[NSString stringWithFormat:@"%ldcm",(long)applier.height]:@"";
    NSString *title = [NSString stringWithFormat:@"%@  %@",city,strH];
    [cell.userSeriesLabel setTitle:title forState:UIControlStateNormal];
    cell.userSeriesLabel.selected = YES;
    cell.acceptBtn.tag = indexPath.row;
    [cell.acceptBtn addTarget:self action:@selector(acceptFriendApply:) forControlEvents:UIControlEventTouchUpInside];

    // 重置remarkLabel高度
    [cell.remarkLabel setFrame:CGRectMake(10, 60, DeviceWidth-20, [Utils LabeSizeLabelheight:friendApply.remark Font:[UIFont fontWithName:FontName size:14]].height +5)];
 
    cell.remarkLabel.text = [NSString stringWithFormat:@"  %@",friendApply.remark];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return  cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MLFriendApply *friendApply = self.friendApplyList[indexPath.row];
    
    MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
    userInfoVC.userData = (MLUser *)friendApply.applier;
    [Utils pushTabbarHidden:userInfoVC Selfvc:self];
    
}

//cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.friendApplyList count];;
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MLFriendApply *friendApply = self.friendApplyList[indexPath.row];
    if (friendApply.remark.length == 0) {
        return 60;
    }else{
        return 70 + [Utils LabeSizeLabelheight:friendApply.remark Font:[UIFont fontWithName:FontName size:14]].height+5;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    // 每个cell的头部间距
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    //每个cell的底部间距
    return 0;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    
    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark user interaction
- (void)addShareDateFriendsUser:(MLUser *)user
{
    //添加为好友
    
    if ([ShareData shareData].friends&&[ShareData shareData].friends.count) {
        //判断是否已经是好友
        BOOL is = NO;
        for (MLUser *f in [ShareData shareData].friends) {
            if([f.objectId isEqualToString:user.objectId]){
                is = YES;
                break;
            }
        }
        
        if (!is) {
              [[ShareData shareData].friends addObject:user];
        }
    }
    [Utils savePassFriendObjectID:user.objectId];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"loadMyFriendsData" object:self userInfo:nil];
    
}
// 接受加好友申请
- (void)acceptFriendApply:(UIButton *)sender {
    [AVAnalytics event:@"我愿意（新的好友）"]; // 通知服务器一个点击事件。

    MLFriendApply *friendApply = self.friendApplyList[sender.tag];
    MLUser *applier = (MLUser *)friendApply.applier;
    //先查询记录是否存在,存在处理,不存在跳过
//    AVQuery *q = [MLFriendApply query];
//    [q whereKey:@"applier" equalTo:friendApply.applier];
//    [q whereKey:@"user" equalTo:friendApply.user];
//    [q whereKey:@"status" equalTo:[NSNumber numberWithInteger:friendApply.status]];
//    [q findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//    
//    }];
    sender.enabled = NO;
    // 修改申请的状态
  //  friendApply.status = MLFriendApplyStatus_SUCCEED;
 //   [friendApply saveInBackground];
    // 加对方为好友
    [[MLUser currentUser] follow:applier.objectId andCallback:^(BOOL succeeded, NSError *error) {
        if (succeeded || error.code == kAVErrorDuplicateValue) {
            [self addShareDateFriendsUser:applier];
            // 通知对方申请成功
            // 给用户发送申请被同意的消息
            [EaseSDKHelper sendTextMessage:@"我同意了让你做我的好友,要好好对我哦" to:applier.objectId messageType:eMessageTypeChat requireEncryption:NO messageExt:nil];
            

            //删除掉所有的好友申请记录
            AVQuery *q1 = [MLFriendApply query];
            [q1 whereKey:@"applier" equalTo:friendApply.applier];
            [q1 whereKey:@"user" equalTo:friendApply.user];
            AVQuery *q2 = [MLFriendApply query];
            [q2 whereKey:@"user" equalTo:friendApply.applier];
            [q2 whereKey:@"applier" equalTo:friendApply.user];
            AVQuery *q = [AVQuery orQueryWithSubqueries:[NSArray arrayWithObjects:q1,q2,nil]];
            [q deleteAllInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
            }];

            
            
            
//            NSDictionary *ext = @{@"type": @EMMESSAGE_EXT_TYPE_CHAT_NOTIFICATION_MSG, @"notification":EMMESSAGE_EXT_NOTI_FRIEND_APPLY_ACCEPTED};
//            NSString *msg = [NSString stringWithFormat:@"%@通过了你的好友申请",[MLUser currentUser].nickname];
//            [ChatSendHelper sendTextMessageWithString:msg
//                                           toUsername:applier.objectId
//                                          isChatGroup:NO
//                                    requireEncryption:NO
//                                                  ext:ext];
            // TODO 给一个申请成功的提示
            NSDictionary *params = @{@"touserId": applier.objectId, @"fromuserId": [MLUser currentUser].objectId,@"nick":[MLUser currentUser].nickname,@"actions":ACTION_FRIEND_APPLY_ACCEPTED};
            [AVCloud callFunctionInBackground:@"sendFriendApplyMsg" withParameters:params block:^(id object, NSError *error) {
                if (object) {
                   
                }
            }];
            // 移除并刷新列表
            [self.friendApplyList removeObject:friendApply];
            [self.tableView reloadData];
            sender.enabled = YES;
            if ([self.friendApplyList count] == 0) {
                _uview.viewPrompt.hidden = NO;
            }else{
                _uview.viewPrompt.hidden = YES;
            }
        }
    }];
}

- (void)rejectAllApply {
    // 忽略所有
    if (![self.friendApplyList count]) {
        [HUD Prompt:@"没有可以忽略的~"];
        return;
    }
    HUD*hud = [[HUD alloc]init];
    [hud HUDImage:nil Title:@"忽略所有" Content:@"确定要忽略所有好友申请?" CANCEL:@"取消" Confirm:@"确定"];
    hud.Confirm  = ^{
        for (MLFriendApply *friendApply in self.friendApplyList) {
            [friendApply deleteInBackground];
        }
        [self.friendApplyList removeAllObjects];
        if (self.friendApplyList.count==0) {
            _uview.viewPrompt.hidden = NO;
        }
        
        // 刷新列表
        [self.tableView reloadData];
    };
    hud.Cancel = ^{
        NSLog(@"取消");
    };
    [self.view addSubview:hud];
}

@end
